package com.song.bloomfilter.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.song.bloomfilter.domain.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class BloomFilterUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 记录到布隆过滤器
     */
    private static String  BLOOM_KEY_PREFIX = "bloom:cache";
    private static String  INFO_KEY = "PRODUCTS:";
    public  boolean cacheBloomFilter(Long id){
        System.out.println(id);
        //先计算它该放在那个位置
        long index = (long) Math.abs((id.hashCode() % Math.pow(2, 32)));
        System.out.println("布隆过滤器位置：" + index);

        return redisTemplate.opsForValue().setBit(BLOOM_KEY_PREFIX, index, true);
    }

    public  boolean getCacheBloomFilter(Long id){
        System.out.println(id);
        //先计算它该放在那个位置
        long index = (long) Math.abs((id.hashCode() % Math.pow(2, 32)));
        System.out.println("布隆过滤器位置：" + index);

        return redisTemplate.opsForValue().getBit(BLOOM_KEY_PREFIX, index);
    }

    /**
     * 添加信息到缓存
     * @param products
     * @return
     */
    public  void cacheInfo(Products products){
        if (products == null){
            return;
        }
        String key = INFO_KEY + products.getProductId();
        redisTemplate.opsForValue().set(key, JSON.toJSONString(products));
    }

    /**
     * 获取缓存信息
     * @param id
     * @return
     */
    public  Products getInfo(Long id){
        String key = INFO_KEY + id;
        String s = redisTemplate.opsForValue().get(key);
        if (s == null){
            return null;
        }
        return JSON.parseObject(s, new TypeReference<Products>() {});
    }
}
